package com.blb.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 调用HTTP接口的案例
 */
public class HttpDemo {

    static String testGet(){
        try {
            URL url = new URL("http://localhost:8080/order-page?current=1&size=5");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            connection.setRequestMethod("GET");
            connection.connect();
            if(connection.getResponseCode() == 200){
                try(BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))){
                    String line = null;
                    StringBuilder stringBuilder = new StringBuilder();
                    while((line = reader.readLine()) != null){
                        stringBuilder.append(line + "\n");
                    }
                    return stringBuilder.toString();
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    static String testPost(){
        try {
            URL url = new URL("http://localhost:8080/order");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            connection.setRequestMethod("POST");
            //设置请求内容类型
            connection.addRequestProperty("Content-Type","application/json");
            //设置输出
            connection.setDoOutput(true);
            //发送参数
            String args = "{\"num\":1,\"goodsId\":1,\"userId\":1,\"time\":\"2020-11-11T11:11:11\"}";
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(args.getBytes("UTF-8"));
            outputStream.flush();
            connection.connect();
            if(connection.getResponseCode() == 200){
                try(BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))){
                    String line = null;
                    StringBuilder stringBuilder = new StringBuilder();
                    while((line = reader.readLine()) != null){
                        stringBuilder.append(line + "\n");
                    }
                    return stringBuilder.toString();
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(testPost());
        System.out.println(testGet());
    }
}
